const fs = require("fs");
const path = require("path");
const router = require("koa-router")();


//查找到文件
function searchfile(fullpath){
    let file = fs.readdirSync(fullpath);
    let finallyfile = file.filter((element)=>{
        return element.endsWith(".js") && element !== "index.js" && element !== "default.js";
    })
    return finallyfile ;
}


//遍历
function registe(files,fullpath){
    files.forEach(element => {
        let tmpPath = path.join(fullpath,element);
        console.log(tmpPath);
        //用orbpath去接收由tmppath组合的路径所暴露的文件
        let orbjpath = require(tmpPath);
        console.log(orbjpath);
        for(let r in orbjpath){
            //输出请求的路由
            console.log(r);
            let type = orbjpath[r][0];
            let fn = orbjpath[r][1];
            if(type === "get"){
                router.get(r,fn);
            }else {
                router.post(r,fn);
            }
        }

    });
}




module.exports= function (){
    let fullpath = __dirname ;
    console.log(fullpath);
    let files = searchfile(fullpath);
    registe(files,fullpath);

    return router.routes();

}